package com.example.recruitment_website.service.Impl;

import com.example.recruitment_website.domain.Wine;
import com.example.recruitment_website.repository.WineRepository;
import com.example.recruitment_website.service.WineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;

@Service
public class WineImpl implements WineService {
    @Autowired
    WineRepository wineRepository;
    @Override
    public Page<Wine> findAll(Pageable pageable) {
        return wineRepository.findAll(pageable);
    }

    @Override
    public Page<Wine> findAllBySort(PageRequest pageRequest, String sort) {
        Specification<Wine> specification = new Specification<Wine>() {
            @Override
            public Predicate toPredicate(Root<Wine> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> wSort = root.get("wine_sort");
                Predicate p =null;
                if(!StringUtils.isEmpty(wSort)){
                    p=criteriaBuilder.equal(wSort, sort);
                }
                return p;
            }
        };
        return wineRepository.findAll(specification,pageRequest);
    }

    @Override
    public Page<Wine> findByKey(PageRequest pageRequest, String key) {
        Specification<Wine> specification = new Specification<Wine>() {
            @Override
            public Predicate toPredicate(Root<Wine> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> wineTitle = root.get("wine_title");
                Predicate p =null;
                if(!StringUtils.isEmpty(wineTitle)){
                    p=criteriaBuilder.like(wineTitle.as(String.class), "%"+key+"%");
                }
                return p;
            }
        };
        return wineRepository.findAll(specification,pageRequest);
    }
}
